﻿#include "CameraScreen_private.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QDebug>

namespace Qly{
CameraScreen_private::CameraScreen_private(CameraScreenInfo &info, QObject *parent) : QThread(parent)
{
    m_screen = info.m_screen;
    m_sleepInterval = 500;
    m_x = 0;
    m_y = 0;
    m_width = -1;
    m_height = -1;
}

CameraScreen_private::CameraScreen_private(QObject *parent) : QThread(parent)
{
    m_screen = nullptr;
    m_sleepInterval = 50;
    m_x = 0;
    m_y = 0;
    m_width = -1;
    m_height = -1;
}

bool CameraScreen_private::openDevice(const CameraScreenInfo &info)
{
    m_screen = info.m_screen;
    return (m_screen);
}

bool CameraScreen_private::openDevice(QScreen *screen)
{
    m_screen = screen;
    return (m_screen);
}

void CameraScreen_private::setFrameRate(double fps)
{
    fps = qBound(0.001, fps, 50.0);
    m_sleepInterval = 1000 / fps;
}

void CameraScreen_private::setRoi(int x, int y, int width, int height)
{
    if(m_screen)
    {
        QRect rect = m_screen->geometry();

        m_x = qBound(0, x, rect.width());
        m_y = qBound(0, y, rect.height());
        m_width = qBound(-1, width, rect.width());
        m_height = qBound(-1, height, rect.height());
    }
}

void CameraScreen_private::run()
{
    while(1)
    {
        if(m_screen)
        {
            QDesktopWidget *desk = QApplication::desktop();
            //qDebug() << "m_width = " << m_width;
            //qDebug() << "m_height = " << m_height;
            QPixmap p = m_screen->grabWindow(desk->winId(), m_x, m_y, m_width, m_height);
            QImage image = p.toImage();
            emit imageChanged(image);
        }
        msleep(m_sleepInterval);
    }
}

QImage CameraScreen_private::capture()
{
    if(m_screen)
    {
        QDesktopWidget *desk = QApplication::desktop();
        QPixmap p = m_screen->grabWindow(desk->winId(), m_x, m_y, m_width, m_height);
        QImage image = p.toImage();
        return image;
    }
    return QImage();
}

void CameraScreen_private::stop()
{
    terminate();
}

void CameraScreen_private::start()
{
    QThread::start(QThread::InheritPriority);
}

}
